package com.gui.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gui.cmn.listener.DictListener;
import com.gui.cmn.mapper.DictMapper;
import com.gui.cmn.service.DictService;
import com.gui.model.cmn.Dict;
import com.gui.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author GodLamp
 * @date 2022/10/13 11:46
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 根据上级id查询子数据列表
     * @param id
     * @return
     */
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        LambdaQueryWrapper<Dict> query = new LambdaQueryWrapper<>();
        query.eq(Dict::getParentId, id);

        List<Dict> list = baseMapper.selectList(query);

        //设置子节点列表中的数据是否还有子节点即设置hasChildren
        for (Dict dict : list) {
            dict.setHasChildren(this.isChildren(dict.getId()));
        }

        return list;
    }

    /**
     * 导出数据字典的数据
     *
     * @param response
     */
    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码，当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //获数据
            List<Dict> dictList = baseMapper.selectList(null);

            //转换数据：Dict转换为DictEeVo
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                //复制转换
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }

            //写
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入数据字典数据
     * @param file
     */
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public String getDictName(String dictCode, String value) {
        //若dictCode为空，则根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value)).getName();
        } else {
            //根据dictCode查询Dict对象，拿到id
            Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));

            //将上一步获取到的id作为父id，查询所有子记录
            Long parentId = dict.getId();

            //根据parent_id与value字段查询
            Dict selectDict = baseMapper.selectOne(
                    new LambdaQueryWrapper<Dict>()
                            .eq(Dict::getParentId, parentId)
                            .eq(Dict::getValue, value)
            );

            return selectDict.getName();
        }
    }

    @Override
    public String getDictName(String value) {
        return this.getDictName("", value);
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));

        return this.findChildData(dict.getId());
    }

    /**
     * 判断指定id下是否还有子节点
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        LambdaQueryWrapper<Dict> query = new LambdaQueryWrapper<>();
        query.eq(Dict::getParentId, id);

        Integer count = baseMapper.selectCount(query);
        return count > 0;
    }
}
